/**
 *  Copyright ( c ) 2009 Quest Agency. All rights reserved
 *  www: http://www.questagency.pl
 *  email: info@questagency.pl
 *  Created by Rafal Szemraj ( rafal@questagency.pl )
 */
package eu.szemraj.managers {
    import eu.szemraj.exception.IllegalArgumentException;    
    
    import flash.events.MouseEvent;    
    import flash.display.Sprite;    
    import flash.ui.Mouse;    
    import flash.display.Stage;    
    
    /**
     *  Quest Agency
     *  www: http://www.questagency.pl
     *  email: info@questagency.pl
     *  @author Rafal Szemraj ( rafal@questagency.pl )
     */
    public class CursorManager {

        private var _stage:Stage;
        private var _currentCursor:Sprite = null;
        
        private static var INSTANCE:CursorManager;
        
        public static function getInstance( stage:Stage = null ):CursorManager {
        	
            return INSTANCE ? INSTANCE : INSTANCE = new CursorManager( stage );
        }

        public function CursorManager( stage:Stage = null ) {
        	
            SingletonManager.checkSingleton( this );
            if( !stage && !_stage )
            	throw new IllegalArgumentException( "no stage assigned to CursorManager" );
            else if( stage )
            	_stage = stage;
        	
        }
        
        public function remove():void {
        	
            if( _currentCursor ) {
                Mouse.show( );
                _stage.removeEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler ); 
            	
                _stage.removeChild( _currentCursor );
                _currentCursor = null;
            }
        }
        
        public function showCursor( cursor:Sprite ):void {
        	
            Mouse.hide();
            _currentCursor = cursor;
            _currentCursor.mouseEnabled = _currentCursor.mouseChildren = false;
            _stage.addChild( _currentCursor );
            _stage.addEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler );
        }
        
        private function mouseMoveHandler(event:MouseEvent):void {
        	
            _currentCursor.x = _stage.mouseX;            _currentCursor.y = _stage.mouseY;
            
            var dummy:Sprite = new Sprite();
            _stage.addChild( dummy );
            _stage.swapChildren( _currentCursor, dummy );
            _stage.removeChild( dummy );
            event.updateAfterEvent();
            Mouse.hide();
        }
    }
}
